<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本文继续上文Dubbo服务提供者启动流程，在上篇文章中详细梳理了基于dubbo spring文件的配置方式，Dubbo是如何加载配置文件，服务提供者dubbo:service标签服务暴露全流程，本节重点关注RegistryProtocol#export中调用doLocalExport方法，其实主要是根据各自协议，服务提供者建立网络服务器，在特定端口建立监听，监听来自消息消费端服务的请求。">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo服务提供者启动流程-下篇">
<meta property="og:url" content="https://www.codingw.net/posts/380ae8bd.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本文继续上文Dubbo服务提供者启动流程，在上篇文章中详细梳理了基于dubbo spring文件的配置方式，Dubbo是如何加载配置文件，服务提供者dubbo:service标签服务暴露全流程，本节重点关注RegistryProtocol#export中调用doLocalExport方法，其实主要是根据各自协议，服务提供者建立网络服务器，在特定端口建立监听，监听来自消息消费端服务的请求。">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdn.net/20180605225624607?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180605225739594?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="article:published_time" content="2020-11-06T14:53:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:09:41.188Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20180605225624607?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/380ae8bd.html"/>





  <title>源码分析Dubbo服务提供者启动流程-下篇 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/380ae8bd.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo服务提供者启动流程-下篇</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-06T22:53:01+08:00">
                2020-11-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/380ae8bd.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo服务提供者启动流程-下篇">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>本文继续上文Dubbo服务提供者启动流程，在上篇文章中详细梳理了基于dubbo spring文件的配置方式，Dubbo是如何加载配置文件，服务提供者dubbo:service标签服务暴露全流程，本节重点关注RegistryProtocol#export中调用doLocalExport方法，其实主要是根据各自协议，服务提供者建立网络服务器，在特定端口建立监听，监听来自消息消费端服务的请求。</p>
<span id="more"></span>

<p>RegistryProtocol#doLocalExport:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">private &lt;T&gt; ExporterChangeableWrapper&lt;T&gt; doLocalExport(final Invoker&lt;T&gt; originInvoker) &#123;</span><br><span class="line">        String key &#x3D; getCacheKey(originInvoker);</span><br><span class="line">        ExporterChangeableWrapper&lt;T&gt; exporter &#x3D; (ExporterChangeableWrapper&lt;T&gt;) bounds.get(key);</span><br><span class="line">        if (exporter &#x3D;&#x3D; null) &#123;</span><br><span class="line">            synchronized (bounds) &#123;</span><br><span class="line">                exporter &#x3D; (ExporterChangeableWrapper&lt;T&gt;) bounds.get(key);</span><br><span class="line">                if (exporter &#x3D;&#x3D; null) &#123;</span><br><span class="line">                    final Invoker&lt;?&gt; invokerDelegete &#x3D; new InvokerDelegete&lt;T&gt;(originInvoker, getProviderUrl(originInvoker));   &#x2F;&#x2F; @1</span><br><span class="line">                    exporter &#x3D; new ExporterChangeableWrapper&lt;T&gt;((Exporter&lt;T&gt;) protocol.export(invokerDelegete), originInvoker);    &#x2F;&#x2F; @2</span><br><span class="line">                    bounds.put(key, exporter);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return exporter;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：如果服务提供者以dubbo协议暴露服务，getProviderUrl(originInvoker)返回的URL将以dubbo://开头。<br>代码@2：根据Dubbo内置的SPI机制，将调用DubboProtocol#export方法。</p>
<h2 id="1、源码分析DubboProtocol-export"><a href="#1、源码分析DubboProtocol-export" class="headerlink" title="1、源码分析DubboProtocol#export"></a>1、源码分析DubboProtocol#export</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">public &lt;T&gt; Exporter&lt;T&gt; export(Invoker&lt;T&gt; invoker) throws RpcException &#123;</span><br><span class="line">        URL url &#x3D; invoker.getUrl();     &#x2F;&#x2F; @1</span><br><span class="line">        &#x2F;&#x2F; export service.</span><br><span class="line">        String key &#x3D; serviceKey(url);      &#x2F;&#x2F; @2</span><br><span class="line">        DubboExporter&lt;T&gt; exporter &#x3D; new DubboExporter&lt;T&gt;(invoker, key, exporterMap);</span><br><span class="line">        exporterMap.put(key, exporter);</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F;export an stub service for dispatching event</span><br><span class="line">        Boolean isStubSupportEvent &#x3D; url.getParameter(Constants.STUB_EVENT_KEY, Constants.DEFAULT_STUB_EVENT);    &#x2F;&#x2F;@3  start</span><br><span class="line">        Boolean isCallbackservice &#x3D; url.getParameter(Constants.IS_CALLBACK_SERVICE, false);                                                  </span><br><span class="line">        if (isStubSupportEvent &amp;&amp; !isCallbackservice) &#123;                                                                                                                        </span><br><span class="line">            String stubServiceMethods &#x3D; url.getParameter(Constants.STUB_EVENT_METHODS_KEY);</span><br><span class="line">            if (stubServiceMethods &#x3D;&#x3D; null || stubServiceMethods.length() &#x3D;&#x3D; 0) &#123;</span><br><span class="line">                if (logger.isWarnEnabled()) &#123;</span><br><span class="line">                    logger.warn(new IllegalStateException(&quot;consumer [&quot; + url.getParameter(Constants.INTERFACE_KEY) +</span><br><span class="line">                            &quot;], has set stubproxy support event ,but no stub methods founded.&quot;));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                stubServiceMethodsMap.put(url.getServiceKey(), stubServiceMethods);                                                                      </span><br><span class="line">            &#125;</span><br><span class="line">        &#125;   &#x2F;&#x2F; @3 end</span><br><span class="line"></span><br><span class="line">        openServer(url);   &#x2F;&#x2F; @4</span><br><span class="line">        optimizeSerialization(url);  &#x2F;&#x2F; @5</span><br><span class="line">        return exporter;                </span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：获取服务提供者URL，以协议名称，这里是dubbo://开头。<br>代码@2：从服务提供者URL中获取服务名，key: interface:port，例如：com.alibaba.dubbo.demo.DemoService:20880。<br>代码@3：是否将转发事件导出成stub。<br>代码@4：根据url打开服务，下面将详细分析其实现。<br>代码@5：根据url优化器序列化方式。</p>
<h2 id="2、源码分析DubboProtocol-openServer"><a href="#2、源码分析DubboProtocol-openServer" class="headerlink" title="2、源码分析DubboProtocol#openServer"></a>2、源码分析DubboProtocol#openServer</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">private void openServer(URL url) &#123;</span><br><span class="line">        &#x2F;&#x2F; find server.</span><br><span class="line">        String key &#x3D; url.getAddress();    &#x2F;&#x2F; @1</span><br><span class="line">        &#x2F;&#x2F;client can export a service which&#39;s only for server to invoke</span><br><span class="line">        boolean isServer &#x3D; url.getParameter(Constants.IS_SERVER_KEY, true);</span><br><span class="line">        if (isServer) &#123;</span><br><span class="line">            ExchangeServer server &#x3D; serverMap.get(key);           &#x2F;&#x2F; @2</span><br><span class="line">            if (server &#x3D;&#x3D; null) &#123;</span><br><span class="line">                serverMap.put(key, createServer(url));                    &#x2F;&#x2F;@3</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                &#x2F;&#x2F; server supports reset, use together with override</span><br><span class="line">                server.reset(url);                                                       &#x2F;&#x2F;@4</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：根据url获取网络地址：ip:port，例如：192.168.56.1:20880，服务提供者IP与暴露服务端口号。<br>代码@2：根据key从服务器缓存中获取，如果存在，则执行代码@4，如果不存在，则执行代码@3.<br>代码@3：根据URL创建一服务器，Dubbo服务提供者服务器实现类为ExchangeServer。<br>代码@4：如果服务器已经存在，用当前URL重置服务器，这个不难理解，因为一个Dubbo服务中，会存在多个dubbo:service标签，这些标签都会在服务台提供者的同一个IP地址、端口号上暴露服务。</p>
<h3 id="2-1-源码分析DubboProtocol-createServer"><a href="#2-1-源码分析DubboProtocol-createServer" class="headerlink" title="2.1 源码分析DubboProtocol#createServer"></a>2.1 源码分析DubboProtocol#createServer</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">private ExchangeServer createServer(URL url) &#123;</span><br><span class="line">        &#x2F;&#x2F; send readonly event when server closes, it&#39;s enabled by default</span><br><span class="line">        url &#x3D; url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString());    &#x2F;&#x2F; @1</span><br><span class="line">        &#x2F;&#x2F; enable heartbeat by default</span><br><span class="line">        url &#x3D; url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT));     &#x2F;&#x2F; @2</span><br><span class="line">        String str &#x3D; url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER);  &#x2F;&#x2F; @3</span><br><span class="line"></span><br><span class="line">        if (str !&#x3D; null &amp;&amp; str.length() &gt; 0 &amp;&amp; !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str))    &#x2F;&#x2F; @4</span><br><span class="line">            throw new RpcException(&quot;Unsupported server type: &quot; + str + &quot;, url: &quot; + url);</span><br><span class="line"></span><br><span class="line">        url &#x3D; url.addParameter(Constants.CODEC_KEY, DubboCodec.NAME);       &#x2F;&#x2F; @5</span><br><span class="line">        ExchangeServer server;</span><br><span class="line">        try &#123;</span><br><span class="line">            server &#x3D; Exchangers.bind(url, requestHandler);    &#x2F;&#x2F; @6</span><br><span class="line">        &#125; catch (RemotingException e) &#123;</span><br><span class="line">            throw new RpcException(&quot;Fail to start server(url: &quot; + url + &quot;) &quot; + e.getMessage(), e);</span><br><span class="line">        &#125;</span><br><span class="line">        str &#x3D; url.getParameter(Constants.CLIENT_KEY);     &#x2F;&#x2F;@7</span><br><span class="line">        if (str !&#x3D; null &amp;&amp; str.length() &gt; 0) &#123;</span><br><span class="line">            Set&lt;String&gt; supportedTypes &#x3D; ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions();</span><br><span class="line">            if (!supportedTypes.contains(str)) &#123;</span><br><span class="line">                throw new RpcException(&quot;Unsupported client type: &quot; + str);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return server;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：为服务提供者url增加channel.readonly.sent属性，默认为true，表示在发送请求时，是否等待将字节写入socket后再返回，默认为true。<br>代码@2：为服务提供者url增加heartbeat属性，表示心跳间隔时间，默认为60*1000，表示60s。<br>代码@3：为服务提供者url增加server属性，可选值为netty,mina等等，默认为netty。<br>代码@4：根据SPI机制，判断server属性是否支持。<br>代码@5：为服务提供者url增加codec属性，默认值为dubbo，协议编码方式。<br>代码@6：根据服务提供者URI,服务提供者命令请求处理器requestHandler构建ExchangeServer实例。requestHandler的实现具体在以后详细分析Dubbo服务调用时再详细分析。<br>代码@7：验证客户端类型是否可用。</p>
<h4 id="2-1-1-源码分析Exchangers-bind-根据URL、ExchangeHandler构建服务器"><a href="#2-1-1-源码分析Exchangers-bind-根据URL、ExchangeHandler构建服务器" class="headerlink" title="2.1.1 源码分析Exchangers.bind 根据URL、ExchangeHandler构建服务器"></a>2.1.1 源码分析Exchangers.bind 根据URL、ExchangeHandler构建服务器</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public static ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException &#123;</span><br><span class="line">        if (url &#x3D;&#x3D; null) &#123;</span><br><span class="line">            throw new IllegalArgumentException(&quot;url &#x3D;&#x3D; null&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        if (handler &#x3D;&#x3D; null) &#123;</span><br><span class="line">            throw new IllegalArgumentException(&quot;handler &#x3D;&#x3D; null&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        url &#x3D; url.addParameterIfAbsent(Constants.CODEC_KEY, &quot;exchange&quot;);</span><br><span class="line">        return getExchanger(url).bind(url, handler);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>上述代码不难看出，首先根据url获取Exchanger实例，然后调用bind方法构建ExchangeServer，Exchanger接口如下<br><img src="https://img-blog.csdn.net/20180605225624607?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"></p>
<ul>
<li>ExchangeServer bind(URL url, ExchangeHandler handler) : 服务提供者调用。</li>
<li>ExchangeClient connect(URL url, ExchangeHandler handler):服务消费者调用。</li>
</ul>
<p>dubbo提供的实现类为：HeaderExchanger，其bind方法如下：</p>
<p>HeaderExchanger#bind</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException &#123;</span><br><span class="line">        return new HeaderExchangeServer(Transporters.bind(url, new DecodeHandler(new HeaderExchangeHandler(handler))));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从这里可以看出，端口的绑定由Transporters的bind方法实现。</p>
<h4 id="2-1-2-源码分析Transporters-bind方法"><a href="#2-1-2-源码分析Transporters-bind方法" class="headerlink" title="2.1.2 源码分析Transporters.bind方法"></a>2.1.2 源码分析Transporters.bind方法</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public static Server bind(URL url, ChannelHandler... handlers) throws RemotingException &#123;</span><br><span class="line">        if (url &#x3D;&#x3D; null) &#123;</span><br><span class="line">            throw new IllegalArgumentException(&quot;url &#x3D;&#x3D; null&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        if (handlers &#x3D;&#x3D; null || handlers.length &#x3D;&#x3D; 0) &#123;</span><br><span class="line">            throw new IllegalArgumentException(&quot;handlers &#x3D;&#x3D; null&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        ChannelHandler handler;</span><br><span class="line">        if (handlers.length &#x3D;&#x3D; 1) &#123;</span><br><span class="line">            handler &#x3D; handlers[0];</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            handler &#x3D; new ChannelHandlerDispatcher(handlers);</span><br><span class="line">        &#125;</span><br><span class="line">        return getTransporter().bind(url, handler);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">public static Transporter getTransporter() &#123;</span><br><span class="line">        return ExtensionLoader.getExtensionLoader(Transporter.class).getAdaptiveExtension();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从这里得知，Dubbo网络传输的接口有Transporter接口实现，其继承类图所示：<br><img src="https://img-blog.csdn.net/20180605225739594?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>本文以netty版本来查看一下Transporter实现。</p>
<p>NettyTransporter源码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public class NettyTransporter implements Transporter &#123;</span><br><span class="line"></span><br><span class="line">    public static final String NAME &#x3D; &quot;netty&quot;;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Server bind(URL url, ChannelHandler listener) throws RemotingException &#123;</span><br><span class="line">        return new NettyServer(url, listener);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Client connect(URL url, ChannelHandler listener) throws RemotingException &#123;</span><br><span class="line">        return new NettyClient(url, listener);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>NettyServer建立网络连接的实现方法为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">protected void doOpen() throws Throwable &#123;</span><br><span class="line">        NettyHelper.setNettyLoggerFactory();</span><br><span class="line">        ExecutorService boss &#x3D; Executors.newCachedThreadPool(new NamedThreadFactory(&quot;NettyServerBoss&quot;, true));</span><br><span class="line">        ExecutorService worker &#x3D; Executors.newCachedThreadPool(new NamedThreadFactory(&quot;NettyServerWorker&quot;, true));</span><br><span class="line">        ChannelFactory channelFactory &#x3D; new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));</span><br><span class="line">        bootstrap &#x3D; new ServerBootstrap(channelFactory);</span><br><span class="line"></span><br><span class="line">        final NettyHandler nettyHandler &#x3D; new NettyHandler(getUrl(), this);      &#x2F;&#x2F; @1</span><br><span class="line">        channels &#x3D; nettyHandler.getChannels();</span><br><span class="line">        &#x2F;&#x2F; https:&#x2F;&#x2F;issues.jboss.org&#x2F;browse&#x2F;NETTY-365</span><br><span class="line">        &#x2F;&#x2F; https:&#x2F;&#x2F;issues.jboss.org&#x2F;browse&#x2F;NETTY-379</span><br><span class="line">        &#x2F;&#x2F; final Timer timer &#x3D; new HashedWheelTimer(new NamedThreadFactory(&quot;NettyIdleTimer&quot;, true));</span><br><span class="line">        bootstrap.setPipelineFactory(new ChannelPipelineFactory() &#123;</span><br><span class="line">            @Override</span><br><span class="line">            public ChannelPipeline getPipeline() &#123;</span><br><span class="line">                NettyCodecAdapter adapter &#x3D; new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);</span><br><span class="line">                ChannelPipeline pipeline &#x3D; Channels.pipeline();</span><br><span class="line">                &#x2F;*int idleTimeout &#x3D; getIdleTimeout();</span><br><span class="line">                if (idleTimeout &gt; 10000) &#123;</span><br><span class="line">                    pipeline.addLast(&quot;timer&quot;, new IdleStateHandler(timer, idleTimeout &#x2F; 1000, 0, 0));</span><br><span class="line">                &#125;*&#x2F;</span><br><span class="line">                pipeline.addLast(&quot;decoder&quot;, adapter.getDecoder());</span><br><span class="line">                pipeline.addLast(&quot;encoder&quot;, adapter.getEncoder());</span><br><span class="line">                pipeline.addLast(&quot;handler&quot;, nettyHandler);     &#x2F;&#x2F; @2</span><br><span class="line">                return pipeline;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        &#x2F;&#x2F; bind</span><br><span class="line">        channel &#x3D; bootstrap.bind(getBindAddress());</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>熟悉本方法需要具备Netty的知识，有关源码：<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/53977445">阅读Netty系列文章</a>，这里不对每一行代码进行解读，对于与网络相关的参数，将在后续文章中详细讲解，本方法@1、@2引起了我的注意，首先创建NettyServer必须传入一个服务提供者URL，但从DubboProtocol#createServer中可以看出，Server是基于网络套接字（ip:port）缓存的，一个JVM应用中，必然会存在多个dubbo:server标签，就会有多个URL，这里为什么可以这样做呢？从DubboProtocol#createServer中可以看出，在解析第二个dubbo:service标签时并不会调用createServer,而是会调用Server#reset方法，是不是这个方法有什么魔法，在reset方法时能将URL也注册到Server上，那接下来分析NettyServer#reset方法是如何实现的。</p>
<h3 id="2-2源码分析DdubboProtocol-reset"><a href="#2-2源码分析DdubboProtocol-reset" class="headerlink" title="2.2源码分析DdubboProtocol#reset"></a>2.2源码分析DdubboProtocol#reset</h3><p>reset方法最终将用Server的reset方法，同样还是以netty版本的NettyServer为例，查看reset方法的实现原理。NettyServer#reset—&gt;父类(AbstractServer)</p>
<p>AbstractServer#reset</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">public void reset(URL url) &#123;</span><br><span class="line">        if (url &#x3D;&#x3D; null) &#123;</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        try &#123;                                                                                                       &#x2F;&#x2F; @1 start</span><br><span class="line">            if (url.hasParameter(Constants.ACCEPTS_KEY)) &#123;</span><br><span class="line">                int a &#x3D; url.getParameter(Constants.ACCEPTS_KEY, 0);</span><br><span class="line">                if (a &gt; 0) &#123;</span><br><span class="line">                    this.accepts &#x3D; a;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Throwable t) &#123;</span><br><span class="line">            logger.error(t.getMessage(), t);</span><br><span class="line">        &#125;</span><br><span class="line">        try &#123;</span><br><span class="line">            if (url.hasParameter(Constants.IDLE_TIMEOUT_KEY)) &#123;</span><br><span class="line">                int t &#x3D; url.getParameter(Constants.IDLE_TIMEOUT_KEY, 0);</span><br><span class="line">                if (t &gt; 0) &#123;</span><br><span class="line">                    this.idleTimeout &#x3D; t;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Throwable t) &#123;</span><br><span class="line">            logger.error(t.getMessage(), t);</span><br><span class="line">        &#125;</span><br><span class="line">        try &#123;</span><br><span class="line">            if (url.hasParameter(Constants.THREADS_KEY)</span><br><span class="line">                    &amp;&amp; executor instanceof ThreadPoolExecutor &amp;&amp; !executor.isShutdown()) &#123;</span><br><span class="line">                ThreadPoolExecutor threadPoolExecutor &#x3D; (ThreadPoolExecutor) executor;</span><br><span class="line">                int threads &#x3D; url.getParameter(Constants.THREADS_KEY, 0);</span><br><span class="line">                int max &#x3D; threadPoolExecutor.getMaximumPoolSize();</span><br><span class="line">                int core &#x3D; threadPoolExecutor.getCorePoolSize();</span><br><span class="line">                if (threads &gt; 0 &amp;&amp; (threads !&#x3D; max || threads !&#x3D; core)) &#123;</span><br><span class="line">                    if (threads &lt; core) &#123;</span><br><span class="line">                        threadPoolExecutor.setCorePoolSize(threads);</span><br><span class="line">                        if (core &#x3D;&#x3D; max) &#123;</span><br><span class="line">                            threadPoolExecutor.setMaximumPoolSize(threads);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125; else &#123;</span><br><span class="line">                        threadPoolExecutor.setMaximumPoolSize(threads);</span><br><span class="line">                        if (core &#x3D;&#x3D; max) &#123;</span><br><span class="line">                            threadPoolExecutor.setCorePoolSize(threads);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Throwable t) &#123;</span><br><span class="line">            logger.error(t.getMessage(), t);</span><br><span class="line">        &#125;              &#x2F;&#x2F; @1 end</span><br><span class="line">        super.setUrl(getUrl().addParameters(url.getParameters()));    &#x2F;&#x2F; @2</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先是调整线程池的相关线程数量，这个好理解。、<br>代码@2：然后设置调用setUrl覆盖原先NettyServer的private volatile URL url的属性，那为什么不会影响原先注册的dubbo:server呢？<br>原来NettyHandler上加了注解：@Sharable，由该注解去实现线程安全。</p>
<p>Dubbo服务提供者启动流程将分析到这里了，本文并未对网络细节进行详细分析，旨在梳理出启动流程，有关Dubbo服务网络实现原理将在后续章节中详细分析，敬请期待。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/cc583494.html" rel="next" title="源码分析Dubbo服务消费端启动流程">
                <i class="fa fa-chevron-left"></i> 源码分析Dubbo服务消费端启动流程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/80b68fd8.html" rel="prev" title="源码分析Dubbo服务提供者启动流程-上篇">
                源码分析Dubbo服务提供者启动流程-上篇 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90DubboProtocol-export"><span class="nav-number">1.</span> <span class="nav-text">1、源码分析DubboProtocol#export</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90DubboProtocol-openServer"><span class="nav-number">2.</span> <span class="nav-text">2、源码分析DubboProtocol#openServer</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90DubboProtocol-createServer"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 源码分析DubboProtocol#createServer</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-1-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90Exchangers-bind-%E6%A0%B9%E6%8D%AEURL%E3%80%81ExchangeHandler%E6%9E%84%E5%BB%BA%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="nav-number">2.1.1.</span> <span class="nav-text">2.1.1 源码分析Exchangers.bind 根据URL、ExchangeHandler构建服务器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-2-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90Transporters-bind%E6%96%B9%E6%B3%95"><span class="nav-number">2.1.2.</span> <span class="nav-text">2.1.2 源码分析Transporters.bind方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90DdubboProtocol-reset"><span class="nav-number">2.2.</span> <span class="nav-text">2.2源码分析DdubboProtocol#reset</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
